import socketserver
import json

class CoupleMakerServer(socketserver.BaseRequestHandler):
    #连接会话字典
    conn_dict = {}
    #用户数据字典
    data_dict={}
    #用学号作为user id 作为会话学生身份辨认
    user_id=""

    def setup(self):
        print("客户端连接：",self.client_address,self.request)

    def save_datas(self,data):
        CoupleMakerServer.data_dict[data["num"]]=data
        print(data["name"]," saved")

    def pairing(self,student_id):
        #配对算法
        print(CoupleMakerServer.data_dict)
        self.request.send(json.dumps(CoupleMakerServer.data_dict, ensure_ascii=False).encode())

    def handle(self):
        while True:
            try:
                conn = self.request
                
                
                # 5.接受客户段发过来的请求
                recv_data= self.request.recv(1024)
                
                 #反序列化
                unserial_data=json.loads(recv_data)
                #添加连接会话字段
                unserial_data["conn"]=conn
                print(unserial_data)
                if  "command" in unserial_data:
                   if "num" in unserial_data:
                       self.user_id=unserial_data["num"]
                       #储存连接会话字典
                       CoupleMakerServer.conn_dict[self.user_id]=self.request

                   if unserial_data["command"]=="pairing":
                       self.pairing(self.user_id)
                                   # 存储数据和会话
                   if unserial_data["command"]=="upload_data":
                       self.save_datas(unserial_data["data"])

            except Exception as e:
                print(self.client_address, e)
                del CoupleMakerServer.conn_dict[self.user_id]
                break

    def send_data(self, conns, data):
        for conn in conns:
            conn.send(data)

if __name__ == '__main__':
    host, port = 'localhost', 21563
    server = socketserver.ThreadingTCPServer((host, port), CoupleMakerServer)
    server.serve_forever()